﻿using System;
using System.Net.Mail;
using System.Text;
using System.Globalization;
using System.Configuration;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.Linq;
using System.Security.Principal;
using System.Web;
using IntraVision.Web;
using IntraVision.Web.Security;
using Model;

public class PrivateOfficeController : LoginController<NotarialServiceDataContext, Person>
{
    public override void Default()
    {
        this.Authorized = new LoginEvent(AddLoginMessageToLog);
        RegisterScript("privateoffice/privateoffice.js");
        _UserSelectCommand = ("Email=@0 and Password=@1 and !IsArchive and IsActivated");
        TemplatePath = "~/views/privateoffice.haml";
        base.Default();
    }

    protected void AddLoginMessageToLog(object user)
    {
        if (user != null)
            EventLog.AddToLog(null, (user as IUser).Id, Request.UserHostAddress.ToString(), EventLogOperationType.ClientLogin);
    }

    public override void  RememberPassword()
    {
        TemplatePath = "~/views/privateoffice.haml";
        LayoutPath = "none";

        string email = Request["email"];

        ViewData["login"] = email;
        if (!String.IsNullOrEmpty(email))
        {
            using (var dc = new NotarialServiceDataContext())
            {
                var person = dc.Persons.FirstOrDefault(p => p.Email == email);
                if (person != null)
                {
                    try
                    {
                        if (!person.IsArchive)
                        {

                            string password = IntraVision.Web.Toolkit.PasswordGenerator.Generate(5);
                            person.Password = RequestHelper.MD5Encode(password);
                            dc.SubmitChanges();

                            string subject = ConfigurationManager.AppSettings["rememberpasswordsubject"] ?? "Изменение пароля";
                            string body = ConfigurationManager.AppSettings["rememberpasswordbody"] ?? String.Format("Ваш временный пароль: %password%{0}Вы можете поменять пароль в разделе регистрационные данные.{0}", Environment.NewLine);
                            body = body.Replace("%password%", password);

                            if (!person.IsActivated)
                            {
                                string link = String.Format(CultureInfo.InvariantCulture, "{0}registration.ivp/activate/{1}/{2}", ViewData["Base"], person.Email, RequestHelper.MD5Encode(person.Email));
                                body += String.Format("Перед началом работы с системой Вам необходимо активировать Вашу учетную запись.{1}Для активации учетной записи кликните по этой ссылке: {0}", link, Environment.NewLine);
                            }

                            try
                            {
                                SendEmail(email, subject, body, false);
                            }
                            catch (Exception ex) { throw ex; }

                            ViewData["message"] = "PASSWORD_SENT";
                        }
                        else
                        {
                            string message = "К сожалению, Ваша учетная запись заблокирована, операция смены пароля запрещена.";
                            ViewData["message"] = message;
                            try
                            {
                                SendEmail(email, "Изменение пароля", message, false);
                            }
                            catch { } 
                        }
                    }
                    catch (Exception ex)
                    {
                        ViewData["message"] = "Не удалось восстановить пароль: " + ex.Message;
                    }
                }
                else
                    ViewData["message"] = "Извините, но данного email нет в нашей БД.";
            }
        }
        else
            ViewData["message"] = "Email не задан.";

        RenderView();
    }

    protected override void AuthorizeViaIdentity()
    {
        ViewData["login"] = "";
        ViewData["password"] = "";
        RenderView();
    }

    protected void SendEmail(string to, string subject, string body, bool isBodyHtml)
    {
        string host = ConfigurationManager.AppSettings["smtphost"] ?? "localhost";
        string from = ConfigurationManager.AppSettings["mailfrom"];
        int port;
        if (!Int32.TryParse(ConfigurationManager.AppSettings["smtpport"], out port))
            port = 25;

        var smtp = new SmtpClient(host, port);
        var mm = new MailMessage(from, to);

        mm.Subject = subject;
        mm.Body = body.Replace("%br%", "<br/>");
        mm.IsBodyHtml = isBodyHtml;

        smtp.Send(mm);
    }

    protected void SendEmail(string to, string subject, string body)
    {
        SendEmail(to, subject, body, true);
    }
}
